package com.thinkcms.freemark.directives;

import com.thinkcms.core.constants.Constants;
import com.thinkcms.core.constants.DirectiveNameEnum;
import com.thinkcms.core.utils.Checker;
import com.thinkcms.freemark.corelibs.directive.AbstractTemplateDirective;
import com.thinkcms.freemark.corelibs.handler.RenderHandler;
import com.thinkcms.service.api.category.CmsCategoryService;
import com.thinkcms.service.dto.category.CmsCategoryDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 根据父分类查询子分类指令
 */
@Component
public class CmsChildCategoryDirective extends AbstractTemplateDirective {

    @Autowired
    CmsCategoryService cmsCategoryService;

    @Override
    public void execute(RenderHandler handler) throws IOException, Exception {
        String pid = handler.getString(Constants.categoryParentId);
        String id = handler.getString(Constants.categoryId);
        List<CmsCategoryDto> childCategorys = new ArrayList<>(16);
        if("0".equals(pid)){ //当前栏目就是父栏目
            childCategorys = cmsCategoryService.selectChildCategory(id);
            if(Checker.BeNotEmpty(childCategorys)){
                childCategorys.get(0).setDefaultCheck(true);
            }
        }else{
            childCategorys = cmsCategoryService.selectChildCategory(pid);
            if(Checker.BeNotEmpty(childCategorys)){
                childCategorys.forEach(childCategory->{
                    childCategory.setDefaultCheck(childCategory.getId().equals(id));
                });
            }
        }
        if(Checker.BeNotBlank(pid)){
          CmsCategoryDto parentCategory= cmsCategoryService.getByPk(pid);
          if(Checker.BeNotNull(parentCategory)){
              handler.put("parentCategory",parentCategory);
          }
        }
        handler.listToMap(getDirectiveName().getCode(),childCategorys).render();
    }

    @PostConstruct
    public void initName(){
        this.setDirectiveName(DirectiveNameEnum.CMS_CHILD_CATEGORY_DIRECTIVE);
    }
}
